// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import { StateMachine } from "../FSMBase/FSMBase";

const { ccclass, property } = cc._decorator;
// 1. 定义状态枚举
enum PlayerState {
    Idle = 'Idle',
    Run = 'Run',
    Jump = 'Jump'
}


@ccclass
export default class fsmStory extends cc.Component {
    // 2. 创建状态机实例
    fsm: StateMachine<PlayerState, string> = new StateMachine<PlayerState, string>();
    init() {

        // 3. 配置状态
        this.fsm.addState(PlayerState.Idle, {
            onEnter: () => console.log('进入待机状态'),
            onUpdate: dt => console.log('待机状态更新')
        })
            .addState(PlayerState.Run, {
                onEnter: () => console.log('开始奔跑')
            })
            .addState(PlayerState.Jump, {
                onEnter: () => console.log('开始跳跃')
            });

        // 4. 配置转换规则
        this.fsm.addTransition(
            PlayerState.Idle,
            PlayerState.Run,
            (event) => event === 'moveStart' // 通过字符串事件触发
        )
            .addTransition(
                [PlayerState.Idle, PlayerState.Run], // 多源状态
                PlayerState.Jump,
                'jump' // 直接匹配事件字符串
            )
            .addTransition(
                PlayerState.Jump,
                PlayerState.Idle,
                this.isGrounded() // 通过条件函数判断
            );

        // 5. 初始化状态
        this.fsm.setState(PlayerState.Idle);

    }
    isGrounded(): string {
        return 'grounded';

    }


    // 6. 在update中持续更新
    update(dt: number) {
        this.fsm.update(dt);
    }

    // 7. 触发状态转换
    onKeyPressed(event: string) {
        this.fsm.trigger(event);
    }
}
